#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理器
用于统一管理所有配置文件的路径和加载
"""

import os
import json
from pathlib import Path
from typing import Dict, Any, Optional

class ConfigManager:
    """配置管理器类"""
    
    def __init__(self, config_dir: str = "config"):
        """
        初始化配置管理器
        Args:
            config_dir: 配置目录路径，默认为"config"
        """
        self.config_dir = Path(config_dir)
        self.config_dir.mkdir(exist_ok=True)
        
        # 定义配置文件路径
        self.config_files = {
            'vbat': self.config_dir / "vbat_config.json",
            'relay': self.config_dir / "relay_config.json",
            'topics': self.config_dir / "test_topics.json",
            'vbat_records': self.config_dir / "vbat_records.json"
        }
    
    def get_config_path(self, config_type: str) -> Path:
        """
        获取指定类型的配置文件路径
        Args:
            config_type: 配置类型 ('vbat', 'relay', 'topics', 'vbat_records')
        Returns:
            Path: 配置文件路径
        """
        if config_type not in self.config_files:
            raise ValueError(f"不支持的配置类型: {config_type}")
        return self.config_files[config_type]
    
    def load_config(self, config_type: str) -> Dict[str, Any]:
        """
        加载配置文件
        Args:
            config_type: 配置类型
        Returns:
            Dict: 配置数据
        """
        config_path = self.get_config_path(config_type)
        
        if not config_path.exists():
            # 如果配置文件不存在，返回空配置
            return {}
        
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"❌ 加载配置文件失败 {config_path}: {e}")
            return {}
    
    def save_config(self, config_type: str, config_data: Dict[str, Any]) -> bool:
        """
        保存配置文件
        Args:
            config_type: 配置类型
            config_data: 配置数据
        Returns:
            bool: 是否保存成功
        """
        config_path = self.get_config_path(config_type)
        
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"❌ 保存配置文件失败 {config_path}: {e}")
            return False
    
    def migrate_config(self, old_path: str, config_type: str) -> bool:
        """
        迁移旧配置文件到新位置
        Args:
            old_path: 旧配置文件路径
            config_type: 配置类型
        Returns:
            bool: 是否迁移成功
        """
        old_file = Path(old_path)
        if not old_file.exists():
            return False
        
        try:
            # 读取旧配置
            with open(old_file, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            # 保存到新位置
            success = self.save_config(config_type, config_data)
            
            if success:
                # 备份旧文件
                backup_path = old_file.with_suffix('.json.backup')
                old_file.rename(backup_path)
                print(f"✅ 配置文件已迁移: {old_path} -> {self.get_config_path(config_type)}")
                print(f"📦 旧文件已备份为: {backup_path}")
            
            return success
            
        except Exception as e:
            print(f"❌ 迁移配置文件失败: {e}")
            return False
    
    def list_configs(self) -> Dict[str, Path]:
        """
        列出所有配置文件及其状态
        Returns:
            Dict: 配置文件信息
        """
        result = {}
        for config_type, config_path in self.config_files.items():
            result[config_type] = {
                'path': config_path,
                'exists': config_path.exists(),
                'size': config_path.stat().st_size if config_path.exists() else 0
            }
        return result
    
    def backup_configs(self, backup_dir: str = "config_backup") -> bool:
        """
        备份所有配置文件
        Args:
            backup_dir: 备份目录
        Returns:
            bool: 是否备份成功
        """
        backup_path = Path(backup_dir)
        backup_path.mkdir(exist_ok=True)
        
        try:
            import shutil
            for config_type, config_path in self.config_files.items():
                if config_path.exists():
                    backup_file = backup_path / f"{config_type}_config_backup.json"
                    shutil.copy2(config_path, backup_file)
            
            print(f"✅ 配置文件已备份到: {backup_path}")
            return True
            
        except Exception as e:
            print(f"❌ 备份配置文件失败: {e}")
            return False
    
    def get_default_config(self, config_type: str) -> Dict[str, Any]:
        """
        获取默认配置
        Args:
            config_type: 配置类型
        Returns:
            Dict: 默认配置数据
        """
        defaults = {
            'vbat': {
                "vbat_monitor_enabled": False,
                "vbat_threshold_low": 3300,
                "vbat_threshold_high": 4500,
                "vbat_max_records": 200,
                "vbat_mqtt_enabled": False,
                "vbat_mqtt_broker": None,
                "vbat_mqtt_port": None,
                "vbat_mqtt_client_id": "vbat_monitor_001",
                "vbat_mqtt_username": "",
                "vbat_mqtt_password": "",
                "vbat_mqtt_topic": None,
                "vbat_mqtt_qos": None,
                "vbat_mqtt_connect_cmd": "AT+ECMTOPEN=0,{broker},{port}",
                "vbat_mqtt_subscribe_cmd": "AT+ECMTSUB=0,{topic},{qos}",
                "vbat_mqtt_publish_cmd": "AT+ECMTPUB=0,{topic},{qos},{json}",
                "vbat_mqtt_disconnect_cmd": "AT+ECMTDISC=0",
                "vbat_mqtt_wait_time": 2000
            },
            'relay': {
                "relay_control_enabled": False,
                "relay_active_level": True,
                "relay_open_before_loop": True,
                "relay_close_after_loop": True,
                "relay_open_delay_ms": 100,
                "relay_close_delay_ms": 100,
                "boot_check_enabled": False,
                "boot_keyword": "Lierda",
                "boot_timeout_ms": 5000
            }
        }
        
        return defaults.get(config_type, {})

# 全局配置管理器实例
config_manager = ConfigManager()